package com.dxy.dxyadmin.config;

import com.dxy.dxyadmin.DO.Admin;
import com.dxy.dxyadmin.service.AdminService;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

//.com maozi 2018-7-29 15:52:35 自定义realm
@Slf4j
public class AdminRealm extends AuthorizingRealm {

    @Autowired
    private AdminService adminService;

    /**
     * 授权
     *
     * @param principalCollection
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        String name = (String) principalCollection.getPrimaryPrincipal();
        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
        // SimpleAuthorizationInfo加入角色名
        authorizationInfo.setRoles(adminService.queryRoles(name));
        // SimpleAuthorizationInfo加入xxx:yyy格式的权限
        authorizationInfo.setStringPermissions(adminService.queryPermissions(name));
        return authorizationInfo;
    }

    /**
     * 认证
     *
     * @param authenticationToken
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        String name = (String) authenticationToken.getPrincipal();
        Admin admin = adminService.findByName(name);
        if (admin == null) {
            // 没找到帐号
            throw new UnknownAccountException();
        }
        return new SimpleAuthenticationInfo(admin.getName(), admin.getPassword(), getName());
    }

}
